package com.tree.common.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

/**
 * @ClassName com.demo.common.util
 * Description: <类功能描述>. <br>
 * <p>
 * <使用说明>
 * </p>
 * @Author tree
 * @Date 2019-05-24 23:51
 * @Version 1.0
 */@Component
public class SpringContextHolder implements ServletContextListener, ApplicationContextAware {

     private static ApplicationContext applicationContext;
     public SpringContextHolder(){
         super();
     }


    @Override
    public void setApplicationContext(ApplicationContext ac) throws BeansException {
        if(applicationContext == null){
            applicationContext = ac;
        }
    }

    @Override
    public void contextInitialized(ServletContextEvent event) {
        applicationContext = WebApplicationContextUtils.getWebApplicationContext(event.getServletContext());
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {

    }

    public static ApplicationContext getApplicationContext(){
         return applicationContext;
    }

    public static <T> T getBean(Class<T> clazz){
         return (T) applicationContext.getBean(clazz);
    }

    public static <T> T getBean(String name){
        return (T) applicationContext.getBean(name);
    }

    public static <T> T getBeanByClassName(String className){
         Class<T> clazz = null;
         try {
             clazz = (Class<T>) Class.forName(className);
         }catch (ClassNotFoundException e){

         }
        return getBean(clazz);
    }

    public static void publishEvent(ApplicationEvent event){
         applicationContext.publishEvent(event);
    }



}
